package socket;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室服务端
 */
public class Server {
    private ServerSocket serverSocket;
    private List<PrintWriter> allOut = new ArrayList<>();

    public Server() {
        try {

            System.out.println("正在启动服务端.....");
            serverSocket = new ServerSocket(8088);// 服务端决定端口号
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        int count = 0;
        Socket socket = null;
        while (true) {
            System.out.println("等待客户端连接。。。。");
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("一个客户端连接了");
            ClientHandLer handLer = new ClientHandLer(socket);
            Thread t = new Thread(handLer);
            t.start();
            count++;
            System.out.println("客户端数量：" + count);
        }
    }

    // }
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    class ClientHandLer implements Runnable {
        private Socket socket;
        private String host;// 记录该客户端的IP地址

        public ClientHandLer(Socket socket) {
            this.socket = socket;// this 一定不能省略
        }

        public void run() {
            PrintWriter pw = null;
            InetAddress address = socket.getInetAddress();
            host = address.getHostAddress();
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);
                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);
                // 成员内部类可以访问外部类的属性
                synchronized (allOut) {// 多线程，不加同步块（synchronized），容易造成数组索引越界异常。
                    allOut.add(pw);// 集合的底层是用数组实现的，数组是定长的。
                }
                System.out.println(host + "上线了，当前在线人数：" + allOut.size());
                String message;
                while ((message = br.readLine()) != null) {
                    System.out.println(host + "说：" + message);
                    synchronized (allOut) {
                        for (PrintWriter o : allOut) {
                            o.println(host + "说：" + message);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                synchronized (allOut) {
                    allOut.remove(pw);
                }
                System.out.println(host + "下线了，当前在线人数：" + allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}


